import { useReducer, useRef, useEffect, KeyboardEvent, MouseEvent } from 'react'
import styled from 'styled-components'
import { EDispatchType, initialGameReducerState, reduceHandler } from './reducer'

const Wrapper = styled.div`
  display: grid;
  place-items: center;
  min-height: 100vh;
  background-color: #444;
  color: white;

  & canvas {
    /* border:1px solid blue; */
    background-color: hsl(210, 70%, 40%);
  }
  & div.action {
    padding-top: .6rem;
    display: flex;
    justify-content: center;
  }
`

const Button: React.FC<React.ButtonHTMLAttributes<HTMLButtonElement>>
= ({children, onClick}) => {
  const ref = useRef<any>(null)
  const clickHandler = (e:MouseEvent<HTMLButtonElement>) => {
    ref.current.blur();
    onClick?.(e);
  }
  return (
    <button ref={ref} onClick={clickHandler}>
      {children}
    </button>
  )
}

export default function Demo () {
  const [ gameState, dispatch ] = useReducer(reduceHandler, initialGameReducerState() );
  const canvasRef = useRef<any>(null)
  const ref = useRef<any>(null);

  useEffect(() => {
    const context = canvasRef.current?.getContext("2d");
    if (!!context) {
      dispatch({
        type: EDispatchType.initial,
        payload: {
          canvasCurrentRef: canvasRef.current,
          context
        }
      })
    }
  }, [])

  const onReset = () => { dispatch({ type: EDispatchType.reset }); }
  const onStart = () => { dispatch({ type: EDispatchType.start }); }
  const onPause = () => { dispatch({ type: EDispatchType.pause }); }
  const onKeyDown = (e: KeyboardEvent<HTMLElement>) => {
    switch(e.key) {
      case ' ':
        if (gameState.status === 'playing') {
          dispatch({ type: EDispatchType.pause });
        } else if (['paused', 'ready'].includes(gameState.status)) {
          dispatch({ type: EDispatchType.start });
        } else if (gameState.status === 'game over') {
          dispatch({ type: EDispatchType.reset });
        }
        break;
      case 'ArrowLeft':
        dispatch({ type: EDispatchType.goLeft });
        break;
      case 'ArrowRight':
        dispatch({ type: EDispatchType.goRight });
        break;
      case 'ArrowUp':
        dispatch({ type: EDispatchType.fire });
        break;
  }
  };
  const onBlur = () => {
    ref.current.focus();
  }

  return (
    <Wrapper tabIndex={0} ref={ref} onKeyDown={onKeyDown} onBlur={onBlur}>
    <div>
      <h1 style={{textAlign: 'center'}}>Raiden Aircraft [{gameState.status}] </h1>
      <canvas ref={canvasRef} width="100" height="100">
        !!! This browser doesn't support canvas !!!
      </canvas>
      <div className='action'>
        { (['ready', 'paused'].includes(gameState.status)) &&
          <Button onClick={onStart}>Start</Button>
        }
        { (gameState.status === 'playing') &&
          <Button onClick={onPause}>Pause</Button>
        }
        { (['paused', 'game over'].includes(gameState.status)) &&
          <Button onClick={onReset}>Reset</Button>
        }
        {/* <Button onClick={onTest}>Test</Button> */}
      </div>
    </div>
    </Wrapper>
  )
}

  // const onTest1 = () => {
  //   const context = canvasRef.current?.getContext("2d");
  //   canvasRef.current.width = 200;
  //   canvasRef.current.height = 300;
  //   const img = new Image(90, 90);
  //   img.src = 'aircraft.svg';
  //   context.drawImage(img, 50, 50, 90, 90);
  // }
  // const onTest = () => {
  //   const width = 200;
  //   const height = 300;
  //   const size = 90;
  //   const angle = 30;
  //   const pos= 50;
  //   const context = canvasRef.current?.getContext("2d");
  //   canvasRef.current.width = width;
  //   canvasRef.current.height = height;
  //   const img = new Image(size, size);
  //   img.src = 'aircraft.svg';

  //   const cvs = document.createElement("canvas");
  //   cvs.width = size;
  //   cvs.height = size;
  //   const ctx = cvs.getContext("2d");
  //   if (!!ctx) {
  //     ctx.save();
  //     ctx.translate(size/2, size/2);
  //     ctx.rotate(angle * Math.PI/180);
  //     ctx.translate(-size/2, -size/2);
  //     ctx.drawImage(img, 0, 0, size, size);
  //     ctx.restore();

  //     context.drawImage(cvs, pos, pos, size, size);
  //   }
  // }
